﻿//NotificationClient.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Algo.Notification
{
	using System;
	using System.ServiceModel;

	using Ecng.Common;
	using Ecng.Net;

	/// <summary>
	/// Клиент для доступа к сервису лицензирование StockSharp.
	/// </summary>
	public class NotificationClient : Disposable
	{
		private readonly Lazy<ChannelFactory<INotificationService>> _factory;
		private Guid _sessionId;

		/// <summary>
		/// Создать <see cref="NotificationClient"/>.
		/// </summary>
		public NotificationClient()
			: this("http://stocksharp.com/services/notificationservice.svc".To<Uri>())
		{
		}

		/// <summary>
		/// Создать <see cref="NotificationClient"/>.
		/// </summary>
		/// <param name="address">Адрес сервиса.</param>
		public NotificationClient(Uri address)
		{
			if (address == null)
				throw new ArgumentNullException("address");

			Address = address;

			_factory = new Lazy<ChannelFactory<INotificationService>>(() =>
			{
				var factory = ChannelHelper.Create("notification", () => new ChannelFactory<INotificationService>(new WSHttpBinding { Security = { Mode = SecurityMode.None } }, new EndpointAddress(address)));

				_sessionId = factory.Invoke(f => f.Login(ServerCredentials.Instance.Login, ServerCredentials.Instance.Password));

				return factory;
			});
		}

		/// <summary>
		/// Адрес сервиса.
		/// </summary>
		public Uri Address { get; private set; }

		/// <summary>
		/// Послать SMS-сообщение.
		/// </summary>
		/// <param name="message">Тело сообщения.</param>
		public void SendSms(string message)
		{
			_factory.Value.Invoke(f => f.SendSms(_sessionId, message));
		}

		/// <summary>
		/// Послать email-сообщение.
		/// </summary>
		/// <param name="caption">Заголовок сообщения.</param>
		/// <param name="message">Тело сообщения.</param>
		public void SendEmail(string caption, string message)
		{
			_factory.Value.Invoke(f => f.SendEmail(_sessionId, caption, message));
		}

		/// <summary>
		/// Освободить занятые ресурсы.
		/// </summary>
		protected override void DisposeManaged()
		{
			if (_factory.IsValueCreated)
			{
				_factory.Value.Invoke(f => f.Logout(_sessionId));
				((IDisposable)_factory.Value).Dispose();
			}

			base.DisposeManaged();
		}
	}
}